/**
 * 腾讯地图微信小程序JSAPI（适配H5）
 *
 * 修改自腾讯地图官方SDK，添加了H5兼容
 */

import Vue from "vue";
import VueJsonp from "vue-jsonp";
Vue.use(VueJsonp);

function QQMapWX(options) {
  if (!options.key) {
    throw Error("key值不能为空");
  }
  this.key = options.key;
}

QQMapWX.prototype.request = function (options) {
  options = options || {};

  // 处理接口域名
  let baseUrl;
  if (options.baseUrl) {
    baseUrl = options.baseUrl;
  } else {
    baseUrl = "https://apis.map.qq.com";
  }

  // 拼接URL
  let url = baseUrl + options.url;

  // 拼接参数
  if (options.data) {
    url += "?";
    for (let key in options.data) {
      url += key + "=" + options.data[key] + "&";
    }
    url = url.substr(0, url.length - 1);
  }

  // 添加key
  url += url.indexOf("?") > -1 ? "&" : "?";
  url += "key=" + this.key;

  // 发起请求
  // 在H5环境中使用JSONP请求，避免跨域问题
  Vue.prototype
    .$jsonp(url, {
      callbackQuery: "callback",
      timeout: 10000, // 设置超时时间，如果10秒后未响应则按失败处理
    })
    .then((response) => {
      if (response.status === 0) {
        options.success && options.success(response);
      } else {
        options.fail && options.fail(response);
      }
    })
    .catch((error) => {
      options.fail &&
        options.fail({
          status: 500,
          message: error.message || "请求失败",
        });
    })
    .finally(() => {
      options.complete && options.complete();
    });
};

// 地点搜索
QQMapWX.prototype.search = function (options) {
  options = options || {};

  // 验证参数
  if (!options.keyword) {
    throw Error("keyword值不能为空");
  }

  const requestOptions = {
    url: "/ws/place/v1/search",
    data: {
      keyword: options.keyword,
    },
  };

  // 处理可选参数
  if (options.boundary) {
    requestOptions.data.boundary = options.boundary;
  }
  if (options.page_size) {
    requestOptions.data.page_size = options.page_size;
  }
  if (options.page_index) {
    requestOptions.data.page_index = options.page_index;
  }

  // 其他可选参数
  const optionalKeys = [
    "orderby",
    "category",
    "filter",
    "region",
    "city_limit",
    "auto_extend",
  ];
  optionalKeys.forEach((key) => {
    if (options[key] !== undefined) {
      requestOptions.data[key] = options[key];
    }
  });

  // 处理回调函数
  ["success", "fail", "complete"].forEach((key) => {
    if (options[key]) {
      requestOptions[key] = options[key];
    }
  });

  this.request(requestOptions);
};

// 关键词输入提示
QQMapWX.prototype.getSuggestion = function (options) {
  options = options || {};

  // 验证参数
  if (!options.keyword) {
    throw Error("keyword值不能为空");
  }

  const requestOptions = {
    url: "/ws/place/v1/suggestion",
    data: {
      keyword: options.keyword,
    },
  };

  // 处理可选参数
  const optionalKeys = [
    "region",
    "region_fix",
    "policy",
    "page_index",
    "page_size",
  ];
  optionalKeys.forEach((key) => {
    if (options[key] !== undefined) {
      requestOptions.data[key] = options[key];
    }
  });

  // 处理回调函数
  ["success", "fail", "complete"].forEach((key) => {
    if (options[key]) {
      requestOptions[key] = options[key];
    }
  });

  this.request(requestOptions);
};

// 逆地址解析
QQMapWX.prototype.reverseGeocoder = function (options) {
  options = options || {};

  // 验证参数
  if (!options.location) {
    throw Error("location不能为空");
  }

  const requestOptions = {
    url: "/ws/geocoder/v1/",
    data: {},
  };

  // 处理位置信息
  if (typeof options.location === "string") {
    requestOptions.data.location = options.location;
  } else {
    requestOptions.data.location =
      options.location.latitude + "," + options.location.longitude;
  }

  // 处理可选参数
  const optionalKeys = ["get_poi", "poi_options", "address_format"];
  optionalKeys.forEach((key) => {
    if (options[key] !== undefined) {
      requestOptions.data[key] = options[key];
    }
  });

  // 处理回调函数
  ["success", "fail", "complete"].forEach((key) => {
    if (options[key]) {
      requestOptions[key] = options[key];
    }
  });

  this.request(requestOptions);
};

// 地址解析
QQMapWX.prototype.geocoder = function (options) {
  options = options || {};

  // 验证参数
  if (!options.address) {
    throw Error("address值不能为空");
  }

  const requestOptions = {
    url: "/ws/geocoder/v1/",
    data: {
      address: options.address,
    },
  };

  // 处理可选参数
  if (options.region) {
    requestOptions.data.region = options.region;
  }

  // 处理回调函数
  ["success", "fail", "complete"].forEach((key) => {
    if (options[key]) {
      requestOptions[key] = options[key];
    }
  });

  this.request(requestOptions);
};

// 城市列表
QQMapWX.prototype.getCityList = function (options) {
  options = options || {};

  const requestOptions = {
    url: "/ws/district/v1/list",
    data: {},
  };

  // 处理回调函数
  ["success", "fail", "complete"].forEach((key) => {
    if (options[key]) {
      requestOptions[key] = options[key];
    }
  });

  this.request(requestOptions);
};

// 获取城市区县列表
QQMapWX.prototype.getDistrictByCityId = function (options) {
  options = options || {};

  if (!options.id) {
    throw Error("id值不能为空");
  }

  const requestOptions = {
    url: "/ws/district/v1/getchildren",
    data: {
      id: options.id,
    },
  };

  // 处理回调函数
  ["success", "fail", "complete"].forEach((key) => {
    if (options[key]) {
      requestOptions[key] = options[key];
    }
  });

  this.request(requestOptions);
};

// 获取离线地图包信息
QQMapWX.prototype.getOfflineMapInfo = function (options) {
  options = options || {};

  const requestOptions = {
    url: "/ws/offlinemap/v1/getofflinemapcitylist",
    data: {},
  };

  // 处理回调函数
  ["success", "fail", "complete"].forEach((key) => {
    if (options[key]) {
      requestOptions[key] = options[key];
    }
  });

  this.request(requestOptions);
};

// 计算距离
QQMapWX.prototype.calculateDistance = function (options) {
  options = options || {};

  // 验证参数
  if (!options.from || !options.to) {
    throw Error("from和to值不能为空");
  }

  const requestOptions = {
    url: "/ws/distance/v1/",
    data: {},
  };

  // 处理起点
  if (typeof options.from === "string") {
    requestOptions.data.from = options.from;
  } else {
    requestOptions.data.from =
      options.from.latitude + "," + options.from.longitude;
  }

  // 处理终点
  if (typeof options.to === "string") {
    requestOptions.data.to = options.to;
  } else if (options.to.constructor === Array) {
    let toArr = [];
    options.to.forEach((item) => {
      if (typeof item === "string") {
        toArr.push(item);
      } else {
        toArr.push(item.latitude + "," + item.longitude);
      }
    });
    requestOptions.data.to = toArr.join(";");
  } else {
    requestOptions.data.to = options.to.latitude + "," + options.to.longitude;
  }

  // 处理可选参数
  if (options.mode) {
    requestOptions.data.mode = options.mode;
  }

  // 处理回调函数
  ["success", "fail", "complete"].forEach((key) => {
    if (options[key]) {
      requestOptions[key] = options[key];
    }
  });

  this.request(requestOptions);
};

export default QQMapWX;
